<!-- 机构编辑弹窗 -->
<template>
  <ele-modal
    :width="620"
    :visible="visible"
    title= "录音播放"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :show-cancel-button="false"
    :show-confirm-button="false"
  >
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="id"
      :toolbar="false"
      :columns="columns"
      :datasource="datasource"
      :scroll="{ x: 560 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="playAudioList(record.path)" :xid="record.id" :currentId="currentId">
              <div v-if="isPlaying && currentId===record.id" class="out">
                <div class="loader"></div>
              </div>
              <div v-else>
                播放
              </div>
            </a>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
    <audio id="audio-player" controls style="display:none;" @ended="handleAudioEnded"></audio>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch, toRefs } from 'vue';
  import { message } from 'ant-design-vue/es';
  import { toDateString } from 'ele-admin-pro';
  import { pageFiles } from '@/api/system/file';

  const emit = defineEmits(['update:visible']);
  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean,
    // 录音文件列表
    recordList: Array
  });

  // 表格实例
  const tableRef = ref(null);

  // 创建音频实例
  const audioPlayer = ref(new Audio());

  // 当前播放音频序号
  const currentIndex = ref(0);
  // 当前播放音频ID
  const currentId = ref(0);

  const isPlaying = ref(false);

  const { recordList } = toRefs(props);

  const audioList = ref(recordList.value ? recordList.value : []);


  // 表格列配置
  const columns = ref([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '操作',
      key: 'action',
      width: 60,
      align: 'center'
    },
    {
      title: '主叫',
      dataIndex: 'callingNo',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      width: 80
    },
    {
      title: '时长',
      dataIndex: 'duration',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      width: 50
    },
    {
      title: '上传时间',
      dataIndex: 'beginTime',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text),
      width: 120
    }
  ]);

  // 表格数据源
  const datasource = () => {
    return Promise.resolve({
      list: audioList.value,
      total: audioList.value.length
    });
  };


  const handleAudioEnded = () => {
    currentIndex.value++;
    console.log("当前音频播放结束，开始下一个,当前播放序号：",currentIndex.value)
    isPlaying.value = false; // 更新播放状态
    playNextAudio()
  }

  audioPlayer.value.addEventListener('ended', handleAudioEnded);
  audioPlayer.value.addEventListener('error', (e) => {
    console.error('音频播放错误：', e);
    // 可以选择在这里处理播放错误，比如尝试播放下一个音频或显示错误消息
  });

  const playNextAudio = () => {
    if(currentIndex.value>=0 && currentIndex.value < audioList.value.length){
      audioPlayer.value.src = audioList.value[currentIndex.value].path
      currentId.value=audioList.value[currentIndex.value].id
      console.log('playAudio====current====',currentIndex.value, currentId.value, audioPlayer.value.src)
      audioPlayer.value.play()
      isPlaying.value = true;
    } else {
      // 播放完所有音频后的处理，比如停止播放或重置索引
      audioPlayer.value.pause();
      currentIndex.value = audioList.value.length-1; // 或者保持为最后一个，取决于需求
      currentId.value=audioList.value[currentIndex.value].id
      isPlaying.value = false;
    }
  }
  const playAudioList = (startSrc) => {
    console.log('playAudioList===',audioList.value)
    const index = audioList.value.findIndex(audio => audio.path === startSrc);
    if (index !== -1) {
      currentIndex.value = index;
      currentId.value=audioList.value[currentIndex.value].id
      playNextAudio();
    } else {
      console.error('未找到匹配的音频文件');
      isPlaying.value = false;
    }
  }

  /* 更新visible */
  const updateVisible = (value) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      console.log('==========watch visible===>',visible)
      if (visible) {
        tableRef.value?.reload?.();
      } else {
        // 关闭时停止播放
        audioPlayer.value.pause();
        isPlaying.value = false;
        currentId.value = null;
      }
    }
  );
  watch(
    () => props.recordList,
    (list) => {
      console.log('==========watch fileRecords===>',list)
      if (list) {
        audioList.value = list.value || list;  // 确保正确赋值
      }
      tableRef.value?.reload?.();
    }
  );
</script>

<style scoped>
  /* 将你的动态图标样式和动画粘贴到这里 */
  .out {
    display: inline-block;
    position: relative;
  }
  .out::before,
  .out::after {
    content: "";
    display: block;
    background-color: #fff;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 999;
    -webkit-clip-path: polygon(100% 0, 0 0, 0 50%);
    clip-path: polygon(100% 0, 0 0, 0 50%);
  }
  .out::after {
    left: 0;
    top: 0;
    -webkit-clip-path: polygon(100% 100%, 0 100%, 0 50%);
    clip-path: polygon(100% 100%, 0 100%, 0 50%);
    background-color: #fff;

  }
  .loader {
    width: 11px;
    height: 22px;
    border-radius: 0px 40px 40px 0px;
    -webkit-mask: repeating-radial-gradient(farthest-side at left, #0000 0, #000 1px 12%, #0000 calc(12% + 1px) 20%);
    background: radial-gradient(farthest-side at left, #514b82 0 95%, #0000 0) left/0% 0% no-repeat #ddd;
    animation: l10 2s infinite steps(6);
  }

  @keyframes l10 {
    100% {
      background-size: 120% 120%
    }
  }
</style>
